﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using Common;
using System.Web.SessionState;
using System.Dynamic;
using Model;
using DAL;
using System.Data;
using System.Dynamic;
using System.Net;
using System.Text;
using System.Web.SessionState;
using JPushAPI;
using WxPayAPI;

namespace UI.tools
{
    /// <summary>
    /// API 的摘要说明
    /// </summary>
    public class API : IHttpHandler, IRequiresSessionState
    {
        static Dictionary<string, Func<int,string>> hs = new Dictionary<string, Func<int,string>>();
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string action = JobRequest.GetRequestString("act");
            string token = JobRequest.GetRequestString("token");
            string result = string.Empty;
            if (Commons.CheckSign())
            {
                int adminid = 0;
                if (!string.IsNullOrEmpty(token))
                {
                    adminid = DataConvert.ToInt(DESEncrypt.Decrypt(token));
                }
                result = hs[action](adminid);
            }
            else
            {
                result = Commons.GetFaild("身份验证失败");
            }
            context.Response.Write(result);
            context.Response.End();
        }
        static API()
        {
            /*首页*/
            #region 获取首页数据
            hs.Add("Init_Index", (int adminid) =>
            {
                //参数
                int source = JobRequest.GetRequestInt("source"); //来源 1.PC  2.Android  3.IOS
                //参数
                List<AdInfo> adlist = AdDAL.FindTop(adminid, 10, 1);
                List<NewsInfo> newslist = new List<NewsInfo>();
                List<EnvironmentInfo> environmentlist = new List<EnvironmentInfo>();
                List<HonorInfo> honorlist = new List<HonorInfo>();
                AdminInfo admin = AdminDAL.FindOneByID(adminid);

                //首页菜单
                List<string> menu = new List<string>();
                menu.Add(admin.Menu1 + "&menu1");
                menu.Add(admin.Menu2 + "&menu2");
                menu.Add(admin.Menu3 + "&menu3");
                menu.Add(admin.Menu4 + "&menu4");
                menu.Add(admin.Menu5 + "&menu5");
                menu.Add(admin.Menu6 + "&menu6");
                menu.Add(admin.Menu7 + "&menu7");
                menu.Add(admin.Menu8 + "&menu8");
                menu.Sort();
                List<string[]> menus = new List<string[]>();
                foreach (string m in menu)
                {
                    menus.Add(m.Split('&'));
                }

                //首页模块
                List<string> square = new List<string>();
                square.Add(admin.Notice + "&notice");
                square.Add(admin.Intro + "&intro");
                square.Add(admin.Cult + "&cult");
                square.Add(admin.Environment + "&environment");
                square.Add(admin.Honor + "&honor");
                List<TagsInfo> tagslist = TagsDAL.FindTop(adminid);
                List<ProductInfo> productlist = new List<ProductInfo>();
                foreach (TagsInfo tags in tagslist)
                {
                    square.Add(tags.Sort + "&" + tags.IsTop + "&" + tags.Count + "&" + tags.Name + "&" + tags.ID + "&tags");
                    List<ProductInfo> plist = ProductDAL.FindTop(adminid, tags.Count, tags.ID.ToString());
                    foreach (ProductInfo p in plist)
                    {
                        if (!productlist.Select(x => x.ID).Contains(p.ID))
                        {
                            productlist.Add(p);
                        }
                    }
                }
                square.Sort();
                List<string[]> squares = new List<string[]>();
                foreach (string m in square)
                {
                    string[] mm = m.Split('&');
                    if (mm[1] == "1") //如果是推荐的，则显示
                    {
                        squares.Add(mm);
                        if (m.Contains("notice"))
                        {
                            newslist=NewsDAL.FindTop(adminid, mm[3], DataConvert.ToInt(mm[2]));
                        }
                        if (m.Contains("environment"))
                        {
                            environmentlist = EnvironmentDAL.FindTop(adminid, DataConvert.ToInt(mm[2]));
                        }
                        if (m.Contains("honor"))
                        {
                            honorlist = HonorDAL.FindTop(adminid, DataConvert.ToInt(mm[2]));
                        }
                    }
                }

                

                dynamic obj = new ExpandoObject();
                obj.admin = admin;
                obj.adlist = adlist;
                obj.newslist = newslist;
                obj.productlist = productlist;
                obj.environmentlist = environmentlist;
                obj.honorlist = honorlist;
                obj.menus = menus;
                obj.squares = squares;
                return Commons.GetSuccess("获取成功", obj);
            });
            #endregion

            /*资讯*/
            #region 获取资讯
            hs.Add("Find_News", (int adminid) =>
            {
                //参数
                int page = JobRequest.GetRequestInt("page"); //第几页
                int newstypeid = JobRequest.GetRequestInt("newstypeid"); //资讯分类
                string keyword = JobRequest.GetRequestString("keyword"); //搜索关键词
                string begindate = JobRequest.GetRequestString("begindate"); //开始时间
                string enddate = JobRequest.GetRequestString("enddate"); //结束时间
                int source = JobRequest.GetRequestInt("source"); //来源 1.PC  2.Android  3.IOS
                //参数
                int count = 0;
                List<NewsInfo> list = NewsDAL.FindPage(newstypeid, keyword, adminid, begindate, enddate, page, Commons.PageSize, "", "", out count);
                foreach (NewsInfo info in list)
                {
                    info.Context = Commons.SubString(Commons.FilterHTML(info.Context),100);
                }
                return Commons.GetSuccess("获取成功", list, count);
            });
            #endregion
            #region 获取资讯详情
            hs.Add("Find_NewsInfo", (int adminid) =>
            {
                //参数
                int id = JobRequest.GetRequestInt("id"); //ID
                int source = JobRequest.GetRequestInt("source"); //来源 1.PC  2.Android  3.IOS
                //参数
                NewsInfo info = NewsDAL.FindOneByID(id);
                NewsDAL.IncClickCount(id);
                return Commons.GetSuccess("获取成功", info);
            });
            #endregion
            #region 获取资讯分类
            hs.Add("Find_NewsType", (int adminid) =>
            {
                //参数
                int source = JobRequest.GetRequestInt("source"); //来源 1.PC  2.Android  3.IOS
                //参数
                List<NewsTypeInfo> list = NewsTypeDAL.FindAll(adminid);
                return Commons.GetSuccess("获取成功", list, list.Count);
            });
            #endregion

            /*商户*/
            #region 获取商户信息
            hs.Add("Find_AdminInfo", (int adminid) =>
            {
                //参数
                int id = JobRequest.GetRequestInt("id"); //ID
                int source = JobRequest.GetRequestInt("source"); //来源 1.PC  2.Android  3.IOS
                //参数
                AdminInfo info = AdminDAL.FindOneByID(id);
                return Commons.GetSuccess("获取成功", info);
            });
            #endregion

            /*留言反馈*/
            #region 保存留言反馈
            hs.Add("Save_Message", (int adminid) =>
            {
                //参数
                int id = JobRequest.GetRequestInt("id"); //唯一ID
                string realname = JobRequest.GetRequestString("realname"); //真实姓名
                string mobile = JobRequest.GetRequestString("mobile"); //电话
                string context = JobRequest.GetRequestString("context"); //内容
                int source = JobRequest.GetRequestInt("source"); //来源 1.PC  2.Android  3.IOS
                //参数
                int ID = 0;
                MessageInfo info = new MessageInfo()
                {
                    ID = id,
                    AdminID = adminid,
                    RealName = realname,
                    Mobile = mobile,
                    Context = context,
                    CreateDate = DateTime.Now
                };
                if (id == 0)
                {
                    ID = MessageDAL.Save(info);
                }
                else
                {
                    ID = MessageDAL.Update(info);
                }
                if (ID > 0)
                {
                    return Commons.GetSuccess("保存成功", ID);
                }
                else
                {
                    return Commons.GetFaild("保存成功");
                }
            });
            #endregion

            /*资质荣誉*/
            #region 获取资质荣誉
            hs.Add("Find_Honor", (int adminid) =>
            {
                //参数
                int source = JobRequest.GetRequestInt("source"); //来源 1.PC  2.Android  3.IOS
                //参数
                int count = 0;
                List<HonorInfo> list = HonorDAL.FindAll(adminid);
                return Commons.GetSuccess("获取成功", list, count);
            });
            #endregion
            #region 获取资质荣誉详情
            hs.Add("Find_HonorInfo", (int adminid) =>
            {
                //参数
                int id = JobRequest.GetRequestInt("id"); //ID
                int source = JobRequest.GetRequestInt("source"); //来源 1.PC  2.Android  3.IOS
                //参数
                HonorInfo info = HonorDAL.FindOneByID(id);
                HonorDAL.IncClickCount(id);
                return Commons.GetSuccess("获取成功", info);
            });
            #endregion

            /*公司环境*/
            #region 获取公司环境
            hs.Add("Find_Environment", (int adminid) =>
            {
                //参数
                int source = JobRequest.GetRequestInt("source"); //来源 1.PC  2.Android  3.IOS
                //参数
                int count = 0;
                List<EnvironmentInfo> list = EnvironmentDAL.FindAll(adminid);
                return Commons.GetSuccess("获取成功", list, count);
            });
            #endregion
            #region 获取公司环境详情
            hs.Add("Find_EnvironmentInfo", (int adminid) =>
            {
                //参数
                int id = JobRequest.GetRequestInt("id"); //ID
                int source = JobRequest.GetRequestInt("source"); //来源 1.PC  2.Android  3.IOS
                //参数
                EnvironmentInfo info = EnvironmentDAL.FindOneByID(id);
                EnvironmentDAL.IncClickCount(id);
                return Commons.GetSuccess("获取成功", info);
            });
            #endregion

            /*产品*/
            #region 获取产品分类
            hs.Add("Find_Category", (int adminid) =>
            {
                //参数
                int source = JobRequest.GetRequestInt("source"); //来源 1.PC  2.Android  3.IOS
                //参数
                List<CategoryInfo> list = CategoryDAL.FindAll(adminid);
                dynamic obj = new ExpandoObject();
                obj.category1 = list.Where(x => x.ParentID == 0);
                obj.category2 = list.Where(x => x.ParentID != 0);
                return Commons.GetSuccess("获取成功", obj);
            });
            #endregion
            #region 获取产品
            hs.Add("Find_Product", (int adminid) =>
            {
                //参数
                int page = JobRequest.GetRequestInt("page"); //第几页
                int category1id = JobRequest.GetRequestInt("category1id"); //大分类ID
                int category2id = JobRequest.GetRequestInt("category2id"); //小分类ID
                string keyword = JobRequest.GetRequestString("keyword"); //搜索关键词
                string begindate = JobRequest.GetRequestString("begindate"); //开始时间
                string enddate = JobRequest.GetRequestString("enddate"); //结束时间
                int source = JobRequest.GetRequestInt("source"); //来源 1.PC  2.Android  3.IOS
                //参数
                int count = 0;
                List<ProductInfo> list = ProductDAL.FindPage(category1id, category2id, keyword, adminid, begindate, enddate, page, Commons.PageSize, "", "", out count);
                return Commons.GetSuccess("获取成功", list, count);
            });
            #endregion

            /*产品详情*/
            #region 获取产品详情
            hs.Add("Find_ProductInfo", (int adminid) =>
            {
                //参数
                int id = JobRequest.GetRequestInt("id"); //ID
                int source = JobRequest.GetRequestInt("source"); //来源 1.PC  2.Android  3.IOS
                //参数
                ProductInfo info = ProductDAL.FindOneByID(id);
                ProductDAL.IncClickCount(id);
                return Commons.GetSuccess("获取成功", info);
            });
            #endregion

            /*广告*/
            #region 获取广告详情
            hs.Add("Find_AdInfo", (int adminid) =>
            {
                //参数
                int id = JobRequest.GetRequestInt("id"); //ID
                int source = JobRequest.GetRequestInt("source"); //来源 1.PC  2.Android  3.IOS
                //参数
                AdInfo info = AdDAL.FindOneByID(id);
                AdDAL.IncClickCount(id);
                return Commons.GetSuccess("获取成功", info);
            });
            #endregion

            /*联系我们*/
            #region 获取联系我们
            hs.Add("Find_Contact", (int adminid) =>
            {
                //参数
                int source = JobRequest.GetRequestInt("source"); //来源 1.PC  2.Android  3.IOS
                //参数
                AdminInfo info = AdminDAL.FindOneByID(adminid);
                List<string[]> contacts = new List<string[]>();
                if (!string.IsNullOrEmpty(info.ContactName))
                {
                    contacts.Add((info.ContactName + "&contactname").Split('&'));
                }
                if (!string.IsNullOrEmpty(info.Phone))
                {
                    contacts.Add((info.Phone + "&phone").Split('&'));
                }
                if (!string.IsNullOrEmpty(info.Mobile))
                {
                    contacts.Add((info.Mobile + "&mobile").Split('&'));
                }
                if (!string.IsNullOrEmpty(info.QQ))
                {
                    contacts.Add((info.QQ + "&qq").Split('&'));
                }
                if (!string.IsNullOrEmpty(info.WeiXin))
                {
                    contacts.Add((info.WeiXin + "&weixin").Split('&'));
                }
                if (!string.IsNullOrEmpty(info.Sina))
                {
                    contacts.Add((info.Sina + "&sina").Split('&'));
                }
                if (!string.IsNullOrEmpty(info.Email))
                {
                    contacts.Add((info.Email + "&email").Split('&'));
                }
                if (!string.IsNullOrEmpty(info.Address))
                {
                    contacts.Add((info.Address + "&address").Split('&'));
                }
                dynamic obj = new ExpandoObject();
                obj.contacts = contacts;
                obj.comname = info.ComName;
                return Commons.GetSuccess("获取成功", obj);
            });
            #endregion

            /*我们*/
            #region 获取我们
            hs.Add("Find_We", (int adminid) =>
            {
                //参数
                int source = JobRequest.GetRequestInt("source"); //来源 1.PC  2.Android  3.IOS
                //参数
                AdminInfo info = AdminDAL.FindOneByID(adminid);
                //我们页菜单
                List<string> we = new List<string>();
                we.Add(info.We1 + "&we1");
                we.Add(info.We2 + "&we2");
                we.Add(info.We3 + "&we3");
                we.Add(info.We4 + "&we4");
                we.Add(info.We5 + "&we5");
                we.Add(info.We6 + "&we6");
                we.Add(info.We7 + "&we7");
                we.Sort();
                List<string[]> wes = new List<string[]>();
                foreach (string m in we)
                {
                    string[] mm = m.Split('&');
                    if (mm[1] == "1") //如果是推荐的，则显示
                    {
                        wes.Add(m.Split('&'));
                    }
                }
                dynamic obj = new ExpandoObject();
                obj.wes = wes;
                obj.comname = info.ComName;
                return Commons.GetSuccess("获取成功", obj);
            });
            #endregion

            /*热门关键词*/
            #region 获取热门关键词
            hs.Add("Find_Hot", (int adminid) =>
            {
                //参数
                int source = JobRequest.GetRequestInt("source"); //来源 1.PC  2.Android  3.IOS
                //参数
                string[] hot = CommonDAL.FindColumnByID(adminid, "Hot", "admin").Replace("，",",").Split(',');
                return Commons.GetSuccess("获取成功", hot);
            });
            #endregion
        }

        //PC用
        public static void UploadAnnex(int sid, int userid, int tableid, string imgs)
        {
            string[] imges = imgs.Split(',');
            if (imgs.Trim() != "")
            {
                foreach (string img in imges)
                {
                    string[] images = img.Split('*');
                    FileInfo file = new FileInfo(HttpContext.Current.Server.MapPath(images[0]));
                    AnnexInfo info = new AnnexInfo()
                    {
                        SID = sid,
                        UserID = userid,
                        Name = images[1],
                        Path = images[0],
                        Size = (int)file.Length,
                        TableID = tableid,
                        Type = 1,
                        CreateDate = DateTime.Now
                    };
                    AnnexDAL.Save(info);
                }
            }
        }
        public static void UploadFile(int sid, int userid, int tableid, string imgs)
        {
            string[] imges = imgs.Split(',');
            if (imgs.Trim() != "")
            {
                foreach (string img in imges)
                {
                    string[] images = img.Split('*');
                    FileInfo file = new FileInfo(HttpContext.Current.Server.MapPath(images[0]));
                    AnnexInfo info = new AnnexInfo()
                    {
                        SID = sid,
                        UserID = userid,
                        Name = images[1],
                        Path = images[0],
                        Size = (int)file.Length,
                        TableID = tableid,
                        Type = 2,
                        CreateDate = DateTime.Now
                    };
                    AnnexDAL.Save(info);
                }
            }
        }
        //手机用
        public static void UploadAnnex(int sid,int userid, int tableid)
        {
            var content = HttpContext.Current;
            string opath = "/upload/" + DateTime.Now.ToString("yyyy-MM-dd") + "/";
            var rootpath = content.Server.MapPath(opath);
            if (!System.IO.Directory.Exists(rootpath))
            {
                Directory.CreateDirectory(rootpath);
            }
            string[] keys = content.Request.Files.AllKeys;
            for (int j = 0; j < content.Request.Files.Count; j++)
            {
                HttpPostedFile uploadFile = content.Request.Files[j];
                if (uploadFile.ContentLength > 0 && keys[j]=="img")
                {
                    string ext = Path.GetExtension(uploadFile.FileName);
                    string unique = DateTime.Now.ToString("HHmmssfff");
                    string file = rootpath + unique + ext;
                    string name = file.Substring(0, file.LastIndexOf('.'));
                    uploadFile.SaveAs(file);
                    string imgpath50 = name + "_50" + ext;
                    string imgpath100 = name + "_100" + ext;
                    string imgpath200 = name + "_200" + ext;
                    string imgpath500 = name + "_500" + ext;
                    string imgpath1000 = name + "_1000" + ext;
                    Thumbnail.MakeThumbnailImage(file, imgpath50, 50, 50);
                    Thumbnail.MakeThumbnailImage(file, imgpath100, 100, 100);
                    Thumbnail.MakeThumbnail(file, imgpath200, 200, 200);
                    Thumbnail.MakeThumbnailImage(file, imgpath500, 500, 500);
                    Thumbnail.MakeThumbnailImage(file, imgpath1000, 1000, 1000);

                    AnnexInfo info = new AnnexInfo()
                    {
                        SID=sid,
                        UserID=userid,
                        Name=uploadFile.FileName,
                        Path = opath + unique + ext,
                        Size=uploadFile.ContentLength,
                        TableID=tableid,
                        Type=1,
                        CreateDate=DateTime.Now
                    };
                    AnnexDAL.Save(info);
                }

                if (uploadFile.ContentLength > 0 && keys[j] == "file")
                {
                    string ext = Path.GetExtension(uploadFile.FileName);
                    string unique = DateTime.Now.ToString("HHmmssfff");
                    string file = rootpath + unique + ext;
                    if (ext == "") { continue; }
                    string name = file.Substring(0, file.LastIndexOf('.'));
                    uploadFile.SaveAs(file);
                    AnnexInfo info = new AnnexInfo()
                    {
                        SID = sid,
                        UserID = userid,
                        Name = uploadFile.FileName,
                        Path = opath + unique + ext,
                        Size = uploadFile.ContentLength,
                        TableID = tableid,
                        Type=2,
                        CreateDate = DateTime.Now
                    };
                    AnnexDAL.Save(info);

                }

            }
        }
        public static string UploadImg()
        {
            var content = HttpContext.Current;
            string opath = "/upload/" + DateTime.Now.ToString("yyyy-MM-dd") + "/";
            var rootpath = content.Server.MapPath(opath);
            if (!System.IO.Directory.Exists(rootpath))
            {
                Directory.CreateDirectory(rootpath);
            }
            string str = "";
            for (int j = 0; j < content.Request.Files.Count; j++)
            {
                HttpPostedFile uploadFile = content.Request.Files[j];
                if (uploadFile.ContentLength > 0)
                {
                    string ext = Path.GetExtension(uploadFile.FileName);
                    string unique = DateTime.Now.ToString("HHmmssfff");
                    string file = rootpath + unique + ext;
                    string name = file.Substring(0, file.LastIndexOf('.'));
                    uploadFile.SaveAs(file);
                    string imgpath50 = name + "_50" + ext;
                    string imgpath100 = name + "_100" + ext;
                    string imgpath200 = name + "_200" + ext;
                    string imgpath500 = name + "_500" + ext;
                    string imgpath1000 = name + "_1000" + ext;
                    Thumbnail.MakeThumbnailImage(file, imgpath50, 50, 50);
                    Thumbnail.MakeThumbnailImage(file, imgpath100, 100, 100);
                    Thumbnail.MakeThumbnail(file, imgpath200, 200, 200);
                    Thumbnail.MakeThumbnailImage(file, imgpath500, 500, 500);
                    Thumbnail.MakeThumbnailImage(file, imgpath1000, 1000, 1000);
                    str = opath + unique + ext;
                }

            }
            return str;
        }
        static string SendSms(string PhoneNumber, string SMSContent)
        {
            string tmp = "";
            if (PhoneNumber != "")
            {
                string accountname = "tianze";
                string accountpwd = "tianze8899";
                Encoding encoding = Encoding.GetEncoding("gb2312");
                string postData = "";
                SMSContent = System.Web.HttpUtility.UrlEncode(SMSContent, System.Text.Encoding.GetEncoding("gb2312"));
                byte[] data = encoding.GetBytes(postData);
                // Prepare web request
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://203.81.21.34//send/gsend.asp?name=" + accountname + "&pwd=" + accountpwd + "&dst=" + PhoneNumber + "&msg=" + SMSContent);
                myRequest.Method = "POST";
                myRequest.Timeout = 10000;
                myRequest.ContentType = "application/x-www-form-urlencoded";
                myRequest.ContentLength = data.Length;
                Stream newStream = myRequest.GetRequestStream();
                // Send the data.
                newStream.Write(data, 0, data.Length);
                newStream.Close();
                //接收返回信息：
                HttpWebResponse response = (HttpWebResponse)myRequest.GetResponse();
                StreamReader sreader = new StreamReader(response.GetResponseStream(), Encoding.Default);
                tmp = sreader.ReadToEnd();
            }
            return tmp;
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}